import React, { useState } from 'react'
import {
  EyeInvisibleOutlined,
  EyeTwoTone,
  SafetyCertificateOutlined,
  UnlockOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { Button, Form, Input, message, Row } from 'antd'
import { history, useModel, useRequest } from 'umi'
import { LoginParamsType } from '@/types/login'
import { fetchLogin } from '@/services/login'
import code from '@/assets/login-code.png'
// import { fetchUserInfo } from '@/services/user'
import { setToken } from '@/utils/auth'
import { ProjectTitle } from '@/common/constants'
import './login.less'

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState')
  const { StorgeSet } = useModel('storge')
  const [form] = Form.useForm<{ username: string; password: string; vercode: string }>()
  const [loading, setLoading] = useState(false)
  const rules = {
    username: [
      { required: true, message: '请填写用户名', trigger: 'blur' },
      { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请填写密码', trigger: 'blur' },
      { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
    ],
    vercode: [{ required: true, message: '请填写验证码', trigger: 'blur' }],
  }

  const handleCaptcha = () => {
    // setCaptch(code)
  }

  const { validateFields } = form
  const onFinish = () => {
    validateFields()
      .then(async (values: LoginParamsType) => {
        loginRequest.run(values)
      })
      .catch((error: any) => {
        console.log('error', error)
        setLoading(false)
      })
  }

  const loginSuccess = async (token: string) => {
    if (initialState && token) {
      const currentUser = await initialState?.getUserInfo?.()
      console.log('currentUser', currentUser)
      currentUser?.username && sessionStorage.setItem(`${ProjectTitle}-username`, currentUser.username)

      StorgeSet({
        path: 'info',
        value: currentUser,
      })
      setToken(token)
      setInitialState({
        ...initialState,
        currentUser,
      })
      history.replace('/')

      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        message.success('Hi, 欢迎回来')
      }, 1000)
    }
  }

  // const userInfo = useRequest(fetchUserInfo)
  // console.log('userInfo', userInfo)

  const loginRequest = useRequest(
    (values: LoginParamsType) => {
      const data = fetchLogin({ ...values })
      return data
    },
    {
      manual: true,
      onSuccess: (data) => {
        if (data?.token) {
          loginSuccess(data.token)
        }
      },
    },
  )

  return (
    <div className="app-login">
      <Form
        className="app-login-form"
        layout="horizontal"
        form={form}
        onFinish={onFinish}
        initialValues={{
          username: 'admin',
          password: '123456',
          vercode: 'HWFB',
        }}
      >
        <Form.Item name="username" rules={rules.username} hasFeedback>
          <Input size="large" autoComplete="off" prefix={<UserOutlined />} placeholder="用户名" />
        </Form.Item>
        <Form.Item name="password" rules={rules.password} hasFeedback>
          <Input.Password
            autoComplete="off"
            size="large"
            prefix={<UnlockOutlined />}
            placeholder="密码"
            iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
          />
        </Form.Item>
        <Form.Item className="imgcode-item">
          <Form.Item name="vercode" rules={rules.vercode}>
            <Input
              className="captch-input"
              size="large"
              maxLength={4}
              autoComplete="off"
              prefix={<SafetyCertificateOutlined />}
              placeholder="图形验证码"
            />
          </Form.Item>
          <span className="captch-wrap" onClick={handleCaptcha}>
            <img src={code} className="captcha" title="图形验证码" alt="图形验证码" />
          </span>
        </Form.Item>
        <Row>
          <Button block size="large" type="primary" htmlType="submit" loading={loading}>
            {' '}
            登录{' '}
          </Button>
        </Row>
      </Form>
    </div>
  )
}
export default Login
